package com.olocat.cjx.nsims.service.impl

import com.olocat.cjx.nsims.dao.UserRepository
import com.olocat.cjx.nsims.pojo.personnel.User
import com.olocat.cjx.nsims.service.UserService
import org.springframework.stereotype.Service
import javax.annotation.Resource

@Service
class UserServiceImpl : UserService {

    @Resource
    lateinit var userRepository: UserRepository
    override fun login(username: String, password: String): User? {
        return userRepository.findByUsernameAndPasswordEquals(username, password)
    }

    override fun getByTelephone(telephone: String): User? {
        return userRepository.findByTelephoneIs(telephone)
    }

    override fun getById(id: String): User? {
        return userRepository.getOne(id)
    }

    override fun editPassword(id: String, old: String, new: String): Boolean {
        val user:User? = userRepository.getOne(id)
        user?.let {
            return if (it.password == old) {
                userRepository.updatePasswordById(id, new)
                true
            } else false
        }
        return false
    }

    override fun editUsername(id:String, username:String) {
        userRepository.updateUsernameById(id,username)
    }

    override fun save(user: User) {
        userRepository.save(user)
    }

    override fun updateEmailById(id: String, email: String) {
        userRepository.updateEmailById(id, email)
    }

    override fun updateTelephonById(id: String, telephone: String) {
        userRepository.updateTelephoneById(id, telephone)
    }

    override fun saveDoctorUser(user: User) {
        userRepository.save(user)
        userRepository.updateRoleSetDoctorByTelephone(user.telephone)
    }

    override fun saveNurseUser(user: User) {
        userRepository.save(user)
        userRepository.updateRoleSetNurseByTelephone(user.telephone)
    }
}
